/************************************************************************
This file is part of Polar4linux
Copyright (C) 2010-2011 Eric jrdn2
Portions Copyright (C) 2007 Matti Juvonen <mpj@iki.fi> (RS400 Tools)
Portions Copyright (C) 2006 Jani Hursti <jani.hursti@hut.fi>,
Portions Copyright (C) 2001-2003 Tom Oliveira e Silva

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
************************************************************************/

#include "IHM.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <sys/stat.h>

IHM::IHM(QString application_path)
{
	setupUi(this);
	internals = new polar4linuxInternals(application_path);
	internals->adv_graph=new advExoGraph(&internals->default_graph_configuration);
	internals->basic_graph=new basicExoGraph(&internals->default_graph_configuration);
	internals->settW = new polarSettings(internals);
	internals->plotW = new polarSessionView(internals);
	internals->statisticsW = new polarStatistics(internals);
	internals->exBuilderW = new polarExBuilder(internals);
	internals->spreadsheetW = new polarSpreadsheet(internals);
	internals->softOpts = new polarSoftwareOptions(internals);

	internals->mainW=this;
	internals->softOpts->initSettings();
	
	label_freemem->setText("");
	calendar->initialize(internals);
	connect(pushButtonSoftOpt, SIGNAL(clicked()), this, SLOT(showSoftwareOptions()));

	connect(pushButtonRetrieveAll, SIGNAL(clicked()), this, SLOT(askConnexion()));
	connect(pushButtonOpts,SIGNAL(clicked()), this, SLOT(showOpts()));
	connect(pushButtonExBuild,SIGNAL(clicked()), this, SLOT(showExBuilder()));

	connect(calendar,SIGNAL(newdate(QDate,int,int)), this, SLOT(plotFile(QDate,int,int)));
	connect(calendar,SIGNAL(newdatePrev(QDate,int)), this, SLOT(previewFile(QDate,int)));
	connect(calendar,SIGNAL(newSummary(QDate)), this, SLOT(plotWeekSum(QDate)));
	connect(pushButtonStats,SIGNAL(clicked()), this, SLOT(plotYearStats()));

	diag=new polarConnexion(internals);
	connect(diag,SIGNAL(connexionDone()),this,SLOT(retrieveAll()));
};

void IHM::askConnexion()
{
	diag->checkConnexion(0); //generic signal caught
}

void IHM::showSoftwareOptions()
{
	internals->softOpts->fill();
	internals->softOpts->show();
}

void IHM::closeEvent(QCloseEvent *)
{
	QCoreApplication::quit();
}

IHM::~IHM()
{
	delete internals->plotW;
	delete internals->statisticsW;
	delete internals->settW;
	delete internals->exBuilderW;
	//delete internals->adv_graph; //deleted by the view of the exercise builder
	//delete internals->basic_graph; //deleted by the view of the exercise builder
	delete diag;
	delete internals;
}

void IHM::showOpts()
{
	internals->settW->askConnexionGet(); //Ask connexion and get
	internals->settW->show();
}

void IHM::showExBuilder()
{
	internals->exBuilderW->askConnexion();
	internals->exBuilderW->show();
}

void IHM::retrieveAll()
{
	diag->drawStatus(tr("Downloading sessions"));
	
	if (internals->IRDAok)
	{
		//1) get general settings for sportzones
		_getGeneralSettings(internals->gs);

		rs400_overview overview;
		rs400_session session;

		unsigned char buf[RS400_MAX_PACKET_SIZE];

		/*int size =*/ RS400_get_overview(buf);
		RS400_parse_overview(buf, overview);
		diag->setMaximum(overview.number_of_sessions-1);
		//calendar->plotCalendar();
		
		QApplication::processEvents();
		// Now download sessions that do not already exist on the disk
		for (unsigned i = 0; i < overview.number_of_sessions; i++)
		{
			diag->setProgress(i);
			RS400_downloadSessionWithPdd(internals->data_path.toStdString(),i,internals->gs,session);
		}
		label_freemem->setText(QString::number(overview.pcFreeMem)+" % "+tr("free memory"));

		calendar->plotCalendar();
	}
	
	if (internals->autodisconnect==true) diag->closeIRDA();
	diag->hide();
}

void IHM::plotYearStats()
{
	internals->statisticsW->show();
	internals->statisticsW->boundsChanged();
}

void IHM::plotWeekSum(QDate thedate)
{
	internals->plotW->clearPage();
	for (int i=0;i<7;i++)
	{
		QDate date=thedate.addDays(i);
		QString disp=internals->data_path+date.toString("yyyyMMdd")+".pdd";
		int intStat = checkFileExistence(disp.toStdString().c_str());
		if (intStat==0)
		{
			rs400_pdd_content toto;
			_readPDD( (char*)disp.toStdString().c_str(), toto);
			
			for (unsigned int j=0;j<toto.dayinfo.nbrExercises;j++)
			{
				sessionGraph* Gr=new sessionGraph(&internals->default_graph_configuration);
				hrm_data tmp2=internals->data.loadFile(internals->data_path.toStdString(),date,j+1);
				Gr->addData(tmp2);
				if (tmp2.has_changed==0)
				{
					internals->plotW->addGraph(Gr);
				}
			}
		}
	}
	internals->plotW->show();
	internals->plotW->plotSession();
	internals->spreadsheetW->updateExerciseList();
}


void IHM::plotFile(QDate thedate,int exnumber, int showmethod)
{
	//if currentselection has changed, total calories too, so : save and replot calendar
	calendar->plotCalendar();
	if (showmethod==0) internals->plotW->clearPage(); //data are saved automatically within destructor

	hrm_data tmp2=internals->data.loadFile(internals->data_path.toStdString(),thedate,exnumber);
	if (tmp2.has_changed==0)
	{
		if (showmethod==1)
		{
			sessionGraph* Gr=dynamic_cast<sessionGraph*>(internals->plotW->view->selectedGraph);
			if (Gr) Gr->addData(tmp2);
		}
		else
		{
			sessionGraph *Gr=new sessionGraph(&internals->default_graph_configuration);
			Gr->addData(tmp2);
			internals->plotW->addGraph(Gr);
		}
	  internals->plotW->show();
	  internals->plotW->plotSession();
		
		internals->spreadsheetW->updateExerciseList();
	}
}



void IHM::previewFile(QDate thedate,int exNum)
{
	int status=internals->hrm4preview.loadDATA(internals->data_path.toStdString(),thedate,exNum);
	if (status==0) internals->plotW->previewHRM(internals->hrm4preview);
}
